package com.ruyuan.seckilling.publish.async.listener;

import com.alibaba.fastjson.JSON;
import com.ruyuan.seckilling.common.ChannelKey;
import com.ruyuan.seckilling.common.FilePathUtils;
import com.ruyuan.seckilling.publish.async.event.PulishResultEvent;
import com.ruyuan.seckilling.publish.async.event.WriteToDiskEvent;
import com.ruyuan.starter.async.AsyncContext;
import com.ruyuan.starter.async.BossEventBus;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import com.ruyuan.starter.async.listener.EventListener;
import com.ruyuan.starter.async.thread.ExecutorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(ChannelKey.CHANNEL_WRITE_TO_DISK)
public class WriteToDiskEventListener implements EventListener<WriteToDiskEvent> {

    @Autowired
    private BossEventBus bossEventBus;

    @Autowired
    private ExecutorService executorService;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof WriteToDiskEvent;
    }

    @Override
    public void onEvent(WriteToDiskEvent event, AsyncContext eventContext) {
        executorService.execute(ChannelKey.CHANNEL_WRITE_TO_DISK, () -> {
            String staticPagePath = event.getStaticPagePath();
            String staticPageContent = event.getStaticPageContent();

            boolean success = true;

            // 确保目录存在
            String parentDir = FilePathUtils.getParentDir(staticPagePath);
            File parent = new File(parentDir);
            if (!parent.exists()) {
                success = parent.mkdirs();
            }

            if (success) {
                // 把页面的内容写到文件中
                File file = new File(staticPagePath);
                try (RandomAccessFile raf = new RandomAccessFile(file, "rw")){
                    raf.write(staticPageContent.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                    success = false;
                }
            }

            log.info("第2步，把文件写到磁盘上, event={}", JSON.toJSONString(event));

            PulishResultEvent e = new PulishResultEvent();
            e.setPageLogId(event.getPageLogId());
            e.setStaticPageId(event.getStaticPageId());
            e.setSuccess(success);
            bossEventBus.publish(ChannelKey.CHANNEL_PUBLISH_RESULT, e, null);
        });
    }
}
